﻿using Swifter.Json;
using Swifter.RW;
using System.Reflection;

namespace SwifterJson
{
    /// <summary>
    /// 类对象与Json字符串的相互转化中，对类对象的成员类型有以下规则
    /// 1，访问权限为public的成员均会被转化
    /// 2，非默认的struct类型，需要编写对应的ValueInterface和ValueInterfaceMaper（例如：UnityEngine.Vector3）
    /// </summary>
    public class XFormatter
    {
        private static string _wpfVersion;

        public static string WPFVersion {
            get {
                if (string.IsNullOrEmpty(_wpfVersion))
                {
                    _wpfVersion = "NodeBasedSkillEditor, Version=" + Assembly.GetExecutingAssembly().GetName().Version.ToString();
                }
                return _wpfVersion;
            }
        }

        public const string UnityCSharpVersion = "Assembly-CSharp, Version=0.0.0.0";


        static JsonFormatter _formatter;
        public static JsonFormatter Formatter {
            get {
                if (_formatter == null)
                {
                    ValueInterface.DefaultObjectInterfaceType = typeof(GenericInterface<>);
                    ValueInterface.AddMaper(new GenericInterfaceMaper());
                    ValueInterface.AddMaper(new Vector2InterfaceMaper());
                    ValueInterface.AddMaper(new Vector3InterfaceMaper());

                    _formatter = new JsonFormatter(JsonFormatterOptions.Indented);
                }
                return _formatter;
            }
        }

        public static string ToJson(object src)
        {
#if UNITY
            return Formatter.Serialize(src);
#else
            var json = Formatter.Serialize(src);
            json = json.Replace(WPFVersion, UnityCSharpVersion);
            return json;
#endif
        }

        public static T FromJson<T>(string json)
        {
#if UNITY
            return Formatter.Deserialize<T>(json);
#else
            json = json.Replace(UnityCSharpVersion, WPFVersion);
            return Formatter.Deserialize<T>(json);
#endif
        }

        public static T Clone<T>(T src)
        {
            var json = ToJson(src);
            var dest = FromJson<T>(json);
            return dest;
        }

    }
}
